package com.mxl.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

/**
 * 自定义shiro的Realm
 */
@Component
public class MyRealm implements Realm {

    /***
     * 自定义的Realm的名称
     * @return
     */
    @Override
    public String getName() {
        return "MyRealm";
    }

    /**
     * 判断这个realm所支持的token
     * @param authenticationToken
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof UsernamePasswordToken;
    }

    /**
     * 登陆逻辑判断
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String password = new String(((char[]) authenticationToken.getCredentials()));
        String username = authenticationToken.getPrincipal().toString();
        if (!"sang".equals(username)) {
            throw new UnknownAccountException("用户不存在");
        }
        if (!"123".equals(password)) {
            throw new IncorrectCredentialsException("密码不正确");
        }
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
